package com.nuc.bigdata.service.impl;

import com.nuc.bigdata.orm.entity.Clicks;
import com.nuc.bigdata.orm.entity.News;
import com.nuc.bigdata.orm.entity.Pictures;
import com.nuc.bigdata.orm.mapper.ClicksMapper;
import com.nuc.bigdata.orm.mapper.NewsMapper;
import com.nuc.bigdata.orm.feign.NewsFeign;
import com.nuc.bigdata.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;

/**
 * @author JackLuo
 * @date 2019/11/18
 */
@Service
public class NewsServiceImpl implements NewsService {

    private final NewsMapper newsMapper;
    private final ClicksMapper clicksMapper;

    @Autowired
    NewsServiceImpl(NewsMapper newsMapper,
                    ClicksMapper clicksMapper){
        this.newsMapper = newsMapper;
        this.clicksMapper = clicksMapper;
    }


    @Override
    public ArrayList<NewsFeign> listNews() {
        ArrayList<NewsFeign> newsFeigns = new ArrayList<>();
        ArrayList<News> newsList = newsMapper.selectAllNews();
        // 从新闻列表中进行遍历
        for(News news: newsList){
            NewsFeign simplifyNews = simplify(news);
            newsFeigns.add(simplifyNews);
        }
        return newsFeigns;
    }

    @Override
    public NewsFeign getNewsByNewsId(String newsId) {
        News news = newsMapper.selectNewsByNewsId(newsId);
        NewsFeign newsFeign = simplify(news);
        Clicks clicks = clicksMapper.selectByNewsId(newsId);
        if (ObjectUtils.isEmpty(clicks)){
            clicks.setClick(1L);
            clicks.setNewsId(newsId);
            clicksMapper.insert(clicks);
        }else {
            // 添加点击次数
            clicksMapper.updateByNewsId(newsId);
        }

        return newsFeign;
    }


    private NewsFeign simplify(News news) {
        NewsFeign newsFeign = new NewsFeign();
        newsFeign.setTitle(news.getTitle());
        newsFeign.setClick(news.getClick().getClick());
        newsFeign.setContent(news.getContent());
        newsFeign.setNewsId(news.getNewsId());
        newsFeign.setCreateTime(news.getCreateTime());
        // 获取新闻对应的图片
        ArrayList<Pictures> pictures = news.getPictures();
        ArrayList<String> pictureIds = new ArrayList<>();
        for(Pictures p:pictures){
            pictureIds.add(p.getPictureId());
        }

        newsFeign.setPictureIds(pictureIds);

        return newsFeign;
    }
}
